#include "MyLogic.h"


MyLogic::MyLogic()
{
    m_isRunning.store(false);
}

MyLogic::~MyLogic()
{

}

void MyLogic::start()
{
    std::thread threadBtm = std::thread(threadReadBtmData, this);

    std::thread threadBtm2Top = std::thread(threadBtmConvert2TopData, this);

    std::thread threadSendTop = std::thread(threadSendTopData, this);

    threadBtm.join();
    threadBtm2Top.join();
    threadSendTop.join();
}

void MyLogic::threadReadBtmData(void *arg)
{
    MyLogic *pMyLogic = static_cast<MyLogic*>(arg);
    pMyLogic->m_isRunning = true;

    int count = 0;

    Packet packet;
    while (1)
    {
        if ( count == 3 )
        {
            printf("Send Btm Data.\n");
            // 写数据
            string str = "Hello";
            packet.m_dataLen = str.length();
            if ( packet.m_pData != nullptr )
            {
                memset(packet.m_pData, 0, packet.m_dataLen);
            }
            packet.m_pData = new char[packet.m_dataLen];
            memcpy(packet.m_pData, str.c_str(), packet.m_dataLen);
            pMyLogic->m_pBtnDataQueue.pushQueue(packet);
            count = 0;
        }

        count++;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

void MyLogic::threadBtmConvert2TopData(void *arg)
{
    MyLogic *pMyLogic = static_cast<MyLogic*>(arg);
    pMyLogic->m_isRunning = true;

    Packet packet;
    Packet topPacket;

    while (1)
    {
        if ( pMyLogic->m_pBtnDataQueue.popQueue(packet) )
        {
            printf("Recv Btm data, convert 2 Top Data. dataLen: %d | str: %s\n", packet.m_dataLen, packet.m_pData);

            topPacket.m_dataLen = packet.m_dataLen;
            if ( topPacket.m_pData != nullptr )
            {
                memset(topPacket.m_pData, 0, packet.m_dataLen);
            }

            topPacket.m_pData = new char[packet.m_dataLen];
            memcpy(topPacket.m_pData, packet.m_pData, topPacket.m_dataLen);

            pMyLogic->m_pTopDataQueue.pushQueue(packet);
        }
    }
}

void MyLogic::threadSendTopData(void *arg)
{
    MyLogic *pMyLogic = static_cast<MyLogic*>(arg);
    pMyLogic->m_isRunning = true;

    Packet packet;
    while (1)
    {
        if ( pMyLogic->m_pTopDataQueue.popQueue(packet) )
        {
            printf("Recv Convert data, send to Top. dataLen: %d | str: %s\n", packet.m_dataLen, packet.m_pData);

        }
    }
}
